package multithreaded;

public class ThreadTest4 {
    public static void main(String[] args) {
        OneAddDiv oneAddDiv = new OneAddDiv();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        oneAddDiv.divOne();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "消费者").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        oneAddDiv.addOne();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "生产者").start();
    }
}

class OneAddDiv {
    private int number = 0;

    public synchronized void addOne() throws InterruptedException {
        if (number != 0) {
            this.wait();
        }
        if (number == 0) {
            number++;
        }
        System.out.println(Thread.currentThread().getName() + ": " + number);
        this.notifyAll();
    }

    public synchronized void divOne() throws InterruptedException {
        if (number == 0) {
            this.wait();
        }
        if (number != 0) {
            number--;
        }
        System.out.println(Thread.currentThread().getName() + ": " + number);
        this.notifyAll();
    }
}